package com.c.ctgproject.ui.storage.car

import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.c.ctgproject.R
import com.c.ctgproject.adapter.storage.StorageCarListAdapter
import com.c.ctgproject.base.BaseActivity
import com.c.ctgproject.entity.storage.StorageCarListEntity
import com.c.ctgproject.entity.storage.StorageListEntity
import com.c.ctgproject.mode.MyConstants
import com.c.ctgproject.utils.*
import kotlinx.android.synthetic.main.activity_storage_car_detail.*

/**
 *作者:LiBW
 *创建日期: 2020/10/20
 *描述: 车辆详细信息
 */
class StorageCarListActivity : BaseActivity(), StorageCarListAdapter.StorageCarCallback {
    private val mViewModel: StorageCarListViewModel by lazy { ViewModelProvider(this)[StorageCarListViewModel::class.java] }
    private val storageId: Int by lazy { intent.getIntExtra(MyConstants.STORAGE_ID, -1) }
    private var page = 1
    private var size = 20
    private val mList = ArrayList<StorageCarListEntity.DataBean.ListBean>()
    private val mAdapter: StorageCarListAdapter by lazy { StorageCarListAdapter(this, mList, this) }
    private var searchText = ""

    override fun event() {
        changeTransparentStatusBar()
        mCarRV.adapter = mAdapter
        mCarRV.layoutManager = LinearLayoutManager(this)

        getData()
        mViewModel.error.observe(this, Observer {
            mRefresh.over()
            loading.dismiss()
            MyLog.d("错误:$it")
            showToast(it)
        })

        mViewModel.result.observe(this, Observer {
            mRefresh.over()
            loading.dismiss()
            MyLog.d("车辆详细信息回调:$it")
            val data = initData(it)
            if (data.status == 0) {
                val entity = getGson().fromJson(it, StorageCarListEntity::class.java).data
                entity?.list?.let { list ->
                    mList.addAll(list)
                    mAdapter.notifyDataSetChanged()
                }
            } else {
                showToast(data.msg)
            }
        })
    }

    private fun getData() {
        loading.show()
        mViewModel.getCarList(storageId, page, size,searchText)
    }

    override fun click() {
        mSearchET.handlerText {
            if (it.isEmpty()) {
                mList.clear()
                page = 1
                getData()
            }
        }

        //搜索
        mSearchTV.setOnClickListener {
            searchText = mSearchET.text.toString()
            page=1
            mList.clear()
            getData()
        }

        mRefresh.setOnLoadMoreListener {
            page++
            getData()
        }
        mRefresh.setOnRefreshListener {
            page = 1
            mList.clear()
            getData()
        }
    }

    override fun getLayout() = R.layout.activity_storage_car_detail

    override fun onItemClick(id: String) {

    }

}